package com.ucode.application.controller.acis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.acis.mode.Anthology;
import com.ucode.acis.mode.Bibliography;
import com.ucode.acis.mode.BibliographyItem;
import com.ucode.acis.mode.Offprint;
import com.ucode.acis.service.AnthologyService;
import com.ucode.acis.service.BibliographyItemService;
import com.ucode.acis.service.BibliographyService;
import com.ucode.acis.service.OffprintService;
import com.ucode.acis.vo.BibliographyItemVo;
import com.ucode.acis.vo.OffprintVo;
import com.ucode.application.form.acis.AnthologyForm;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.application.vo.acis.BibliographyVo;
import com.ucode.oss.model.FileInfo;
import com.ucode.oss.service.FileInfoService;
import com.ucode.springboot.starter.web.validator.group.AddGroup;
import com.ucode.springboot.starter.web.validator.group.UpdateGroup;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="ACIS-书目")
@RestController
@RequestMapping("/acis-bibliography")
@Validated
public class BibliographyController {
    
    @Autowired
    private AnthologyService anthologyService;
    @Autowired
    private BibliographyService bibliographyService;
    @Autowired
    private BibliographyItemService bibliographyItemService;
    @Autowired
    private OffprintService offprintService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;

    @PreAuthorize("hasAuthority('acis:bibliography:list') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation("列表")
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(
            @ApiParam(value ="名称",required=false)  @RequestParam(value = "name",required=false) String name,
            @ApiParam(value ="类型:1.套装2.单行本",required=false)  @RequestParam(value = "type",required=false) Integer type,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Paginator<Bibliography> paginator = bibliographyService.queryPage(name, type ,pageNum, pageSize);
       
        return ResponseResult.success(paginator);
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:detail') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="详情信息")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/detail/{id}")
    public ResponseResult<Object> detail(@PathVariable(name="id",required=true) Long id){
        
        Bibliography bibliography = bibliographyService.findById(id);
        
        if(bibliography == null || bibliography.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        FileInfo coverFile = fileInfoService.findById(bibliography.getCoverId());
        return ResponseResult.success(new BibliographyVo(bibliography, coverFile));
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:detail') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation("书目关联列表")
    @GetMapping(value = "/items")
    public ResponseResult<Object> items(
            @ApiParam(value ="选集Id",required=true)  @RequestParam(value = "bibliographyId",required=true) Long bibliographyId,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Paginator<BibliographyItem> paginator = bibliographyItemService.queryPage(bibliographyId, pageNum, pageSize);
        
        Paginator<BibliographyItemVo> vopage = new Paginator<>(paginator.getTotal(), paginator.getCurrentPage(), paginator.getRows());
        if(CollUtil.isNotEmpty(paginator.getList())){
            Bibliography bibliography = bibliographyService.findById(bibliographyId);
            
            List<Long> itemIds=  paginator.getList().stream().map(BibliographyItem::getItemId).collect(Collectors.toList());
            Map<Long, String> itemMap = null;
            //类型:1.套装2.单行本
            if(bibliography.getType() == 1){
                List<Anthology> anthologies = anthologyService.findByIds(itemIds);
                if(CollUtil.isNotEmpty(anthologies)){
                    itemMap = anthologies.stream().collect(Collectors.toMap(Anthology::getId,Anthology::getName,(key1, key2) -> key1));
                }
            }else{
                List<Offprint> offprints = offprintService.findByIds(itemIds);
                if(CollUtil.isNotEmpty(offprints)){
                    itemMap = offprints.stream().collect(Collectors.toMap(Offprint::getId,Offprint::getName,(key1, key2) -> key1));
                }
            }
            
            List<BibliographyItemVo> vos = new ArrayList<BibliographyItemVo>();
            for (BibliographyItem bibliographyItem : paginator.getList()) {
                String name = itemMap != null ? itemMap.get(bibliographyItem.getItemId()) : null;
                vos.add(new BibliographyItemVo(bibliographyItem,name));
            }
            vopage.setList(vos);
        }
        return ResponseResult.success(vopage);
    }
    
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="根据主键查询")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/getById/{id}")
    public ResponseResult<Object> getById(@PathVariable(name="id",required=true) Long id){
        
        Bibliography bibliography = bibliographyService.findById(id);
        
        if(bibliography == null || bibliography.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }
        
        FileInfo coverFile = fileInfoService.findById(bibliography.getCoverId());
        return ResponseResult.success(new BibliographyVo(bibliography, coverFile));
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation("单行本选择列表")
    @GetMapping(value = "/offprints")
    public ResponseResult<Object> works(
            @ApiParam(value ="关键字",required=false)  @RequestParam(value = "keywords",required=false) String keywords,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Paginator<OffprintVo> paginator = offprintService.queryPage(keywords, null, null, pageNum, pageSize);
        return ResponseResult.success(paginator);
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation("选集选择列表")
    @GetMapping(value = "/anthologys")
    public ResponseResult<Object> anthologys(
            @ApiParam(value ="关键字",required=false)  @RequestParam(value = "keywords",required=false) String keywords,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Paginator<Anthology> paginator = anthologyService.queryPage(keywords, pageNum, pageSize);
        return ResponseResult.success(paginator);
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="创建")
    @PostMapping("/create")
    public ResponseResult<Object> create(@Validated({AddGroup.class}) @RequestBody AnthologyForm form) {
        
        Anthology anthology = form.build();
        int i = anthologyService.insert(anthology);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="更新")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/update/{id}")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
            @Validated({UpdateGroup.class}) @RequestBody AnthologyForm form) {
        
        Anthology anthology = form.build();
        anthology.setId(id);
        int i = anthologyService.update(anthology);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="添加书目内容项")
    @PostMapping("/addItems")
    public ResponseResult<Object> addItems(
            @ApiParam(value="书目Id",required=true)@RequestParam(value = "bibliographyId", required=true) Long bibliographyId,
            @ApiParam(value="内容项Ids",required=true) @Size(min = 1,max=20,message="一次添加1-20人")@RequestParam(value = "itemIds", required=true) List<Long> itemIds) {
        bibliographyItemService.batchSave(bibliographyId, itemIds);
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('acis:bibliography:edit') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="删除书目内容项")
    @PostMapping("/deleteItems")
    public ResponseResult<Object> deleteItems(
            @ApiParam(value="Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        bibliographyItemService.delete(ids);
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('acis:anthology:delete') or hasRole('ACISADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="删除")
    @PostMapping("/delete")
    public ResponseResult<Object> delete(
            @ApiParam(value="Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        bibliographyService.delete(ids);
        return ResponseResult.success();
    }
    
}
